package com.nuanshui.heatedloan.credit.pay.behavior;

import com.aipg.common.AipgReq;
import com.aipg.common.AipgRsp;
import com.aipg.payreq.AIPG;
import com.aipg.payreq.Body;
import com.alibaba.fastjson.JSON;
import com.nuanshui.heatedloan.credit.pay.*;
import com.nuanshui.heatedloan.credit.pay.annotation.PayBehaviorAttribute;
import com.nuanshui.heatedloan.credit.pay.constant.OrderPayState;
import com.nuanshui.heatedloan.credit.pay.constant.PayBehaviorType;
import com.nuanshui.heatedloan.credit.pay.utils.AllinPayUtil;
import com.nuanshui.heatedloan.credit.pay.validation.ValidationResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 开始发送报文数据
 */
@PayBehaviorAttribute(value= PayBehaviorType.BatchPayExecuteBehavior,order=351)
public class BatchPayExecuteBehavior extends PayBehavior {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private AllinPayTool allinPayTool;

    @Override
    public void internalInvoke(PayRequest request) {

        if(PayContext.getContext().isSuccess())
        {
            return;
        }

        AipgRsp rsp=PayContext.getContext().getAipgRsp();
        if(rsp==null)
            return;
        if(!AllinPayResultCode.isBankChannelNotSupport(rsp))
            return;

        String batchRequestCode=TransRequestCode.getBatchPayCode(request.getTransRequestCode());
        request.setBatchTransRequestCode(batchRequestCode);

        AllinPayUtil.logOrderPay(logger, request, "通联支付通信批量支付发起开始");

        AipgReq aipgReq= PayContext.getContext().getAipgReq();

        AIPG aipg=new AIPG();
        aipg.setINFO(aipgReq.getINFO());
        aipgReq.getINFO().setREQ_SN(AllinPayUtil.getReqSn(aipgReq.getINFO().getMERCHANT_ID()));

        String batchTrxCode=TransRequestCode.getBatchPayCode(request.getTransRequestCode());

        aipgReq.getINFO().setTRX_CODE(batchTrxCode);

        aipg.setBODY((Body) request.getTrxData());


        allinPayTool.sendReq(aipg);

        rsp=PayContext.getContext().getAipgRsp();

        AllinPayUtil.logOrderPay(logger, request, "通联支付通信批量支付发起结束: 请求数据："+ JSON.toJSONString(aipg));
        AllinPayUtil.logOrderPay(logger, request, "通联支付通信批量支付发起结束: 返回数据："+ JSON.toJSONString(rsp));
    }

    @Override
    public void internalValidate(ValidationResult result,PayRequest request) {
        super.internalValidate(result, request);
    }
}
